package com.showboom.elauncher.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.showboom.elauncher.MyAppliacation;
import com.showboom.elauncher.R;
import com.showboom.elauncher.receiver.NetReceiver;
import com.showboom.elauncher.receiver.WaKuangStatusReceiver;
import com.showboom.elauncher.util.CommandExecution;
import com.showboom.elauncher.util.HmSharedPreferencesUtils;
import com.showboom.elauncher.util.HttpUtils;
import com.showboom.elauncher.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends Activity implements View.OnClickListener {

    public static final int MSG_CHECK_SIM_STATUS = 1001;
    public static final int MSG_SIM_ABSENT = 203;
    public static final int MSG_SHOW_NONET_DIALOG = 111;
    public static final int MSG_DISMISS_NONET_DIALOG = 222;
    public static final int MSG_SIM_ERROR = 333;

    PackageManager packageManager;
    TextView tvDesc, tvStep1, tvStep2, tvStep3, tvSetupHint;
    Button btnStart, btnSignin, btnNext;
    WaKuangStatusReceiver receiver;
    NetReceiver netReceiver;
    View siginLayout, startWorkLayout, mainView;
    final String strDesc = "用<font color='#008FDF'>本机专用手机卡</font>申请<font color='#00b90c'>专用微信号</font>";
    final String step1 = "完成专用微信号注册并进行<font color='#008FDF'>实名认证，绑定银行卡</font>";
    final String step2 = "为了保证挖矿手机能够正常挖矿请将<font color='#008FDF'>微信支付密码</font>设置为以下密码，此密码已经进行加密，不会泄露。";
    final String step3 = "完成实名认证以后请您把<font color='#008FDF'>银行卡解除绑定</font>";
    public static boolean simStatus = false;
    Dialog noNetDialog, simErrorDialog;
    public boolean firstBoot = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initView();
        initData();
        mHandler.sendEmptyMessageDelayed(MSG_CHECK_SIM_STATUS, 20 * 1000);
    }

    private void initView() {
        mainView = findViewById(R.id.main_view);
        tvDesc = findViewById(R.id.main_desc);
        tvDesc.setText(Html.fromHtml(strDesc));
        tvStep1 = findViewById(R.id.tv_step1);
        tvStep1.setText(Html.fromHtml(step1));
        tvStep2 = findViewById(R.id.tv_step2);
        tvStep2.setText(Html.fromHtml(step2));
        tvStep3 = findViewById(R.id.tv_step3);
        tvStep3.setText(Html.fromHtml(step3));
        btnStart = findViewById(R.id.btn_start);
        btnStart.setOnClickListener(this);

        btnSignin = findViewById(R.id.btn_sigin);
        btnSignin.setOnClickListener(this);

        tvSetupHint = findViewById(R.id.tv_setup_hint);
        tvSetupHint.setOnClickListener(this);

        btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(this);

        siginLayout = findViewById(R.id.sigin_layout);
        startWorkLayout = findViewById(R.id.start_work_layout);
        //simCheckTast.execute();
    }

    private void initData() {
        packageManager = getPackageManager();
        receiver = new WaKuangStatusReceiver(mHandler);
        netReceiver = new NetReceiver(mHandler);
        MyAppliacation.setHandler(mHandler);
        registerReceiver();
        writeIMEItoDB();
        Log.d("leihuiming", "oncreate screenOn");
        //screenOn();
        Settings.System.putInt(MyAppliacation.context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 100);
    }

    private void writeIMEItoDB() {
        String imei = Util.getImei(this);
        if (!TextUtils.isEmpty(imei)) {
            Settings.System.putString(getContentResolver(), "deviceIdentity", imei);
        }
    }

    public void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WaKuangStatusReceiver.ACTION_AUTHENTICATION);
        //filter.addAction(WaKuangStatusReceiver.ACTION_SIGNIN);
        filter.addAction(WaKuangStatusReceiver.ACTION_SIGNIN_SHOWBOOM);
        filter.addAction(WaKuangStatusReceiver.ACTION_ERROR);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(receiver, filter);
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int workStatus = Settings.System.getInt(MyAppliacation.context.getContentResolver(), "showboom_work_status", 0);
            switch (msg.what) {
                case WaKuangStatusReceiver.MESSAGE_SIGNIN_STATUS:
                    boolean signin = (boolean) HmSharedPreferencesUtils.getParam("signin", false);
                    Log.d("leihuiming", "handleMessage signin=" + signin);
                    if (signin) {
                        showStartWorkLayout();
                    } else {
                        showSiginErrorLayout();
                        if (workStatus == 1) {
                            sendException("unsignin");
                            updateWorkStatus(0);
                        }
                    }
                    break;
                case WaKuangStatusReceiver.MESSAGE_AUTHENTICATION:
                    boolean auth = (boolean) HmSharedPreferencesUtils.getParam("authentication", false);
                    if (auth) {
                        showStartWorkLayout();
                    } else {
                        showAuthErrorLayout();
                        if (workStatus == 1) {
                            sendException("unauthentication");
                            updateWorkStatus(0);
                        }
                    }
                    break;
                case WaKuangStatusReceiver.MESSAGE_ERROR:
                    if (workStatus == 1) {
                        sendException("unknowException");
                    }
                    updateWorkStatus(0);
                    Log.d("leihuiming", "unknow exception!");
                    break;
                case NetReceiver.MESSAGE_CHECK_STATUS:
                    updateScreenStatus();
                    break;
                case MSG_SHOW_NONET_DIALOG:
                    if (noNetDialog == null) {
                        noNetDialog = NoNetDialog.createNoNetDialog(MainActivity.this);
                    } else {
                        if (!noNetDialog.isShowing()) {
                            noNetDialog.show();
                        }
                    }
                    break;
                case MSG_DISMISS_NONET_DIALOG:
                    if (noNetDialog != null && noNetDialog.isShowing()) {
                        noNetDialog.dismiss();
                        if (!isFirstOpen()) {
                            startWork();
                        }
                    }
                    break;
                case MSG_CHECK_SIM_STATUS:
                    if(workStatus == 1) {
                        screenOff();
                    }

                    new SimCheckTask().execute();
                    break;
                case MSG_SIM_ABSENT:
                    Log.d("leihuiming", "no sim broadcast.");
                    if (workStatus == 1) {
                        sendException("nosim");
                        updateWorkStatus(0);
                    }
                    break;
                case MSG_SIM_ERROR:
                    SimErrorDialog.createLoackScreenDialog(MainActivity.this);
                    sendException("nosim");
                    updateWorkStatus(0);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(firstBoot) {
            //首次开机不检测，设置亮度反应慢
            firstBoot = false;
            if(!isFirstOpen()) {
                if (!MyAppliacation.signinStatus) {
                    showSiginErrorLayout();
                } else {
                    showStartWorkLayout();
                }
            } else {
                if (!MyAppliacation.signinStatus) {
                    showSiginLayout();
                } else {
                    showStartWorkLayout();
                }
            }
        } else {
            updateScreenStatus();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sigin:
                startApp("com.tencent.mm");
                break;
            case R.id.btn_start:
                int workStatus = Settings.System.getInt(MyAppliacation.context.getContentResolver(), "showboom_work_status", 0);
                if (workStatus == 0) {
                    startWork();
                } else {
                    Toast.makeText(this, "设备正在工作，请勿重复点击！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_setup_hint:
                showSiginLayout();
                break;
            case R.id.btn_next:
                showStartWorkLayout();
                break;
            default:
                break;
        }
    }

    static final String[] errorCommands = {"am force-stop com.touchsprite.android", "input keyevent HOME"};

    public static void updateWorkStatus(int status) {
        if (status == 1) {
            screenOff();
            HmSharedPreferencesUtils.setParam("firstOpen", false);
        } else {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    CommandExecution.execCommand(errorCommands, true);
                }
            }.start();
            screenOn();
        }
        int workStatus = Settings.System.getInt(MyAppliacation.context.getContentResolver(), "showboom_work_status", 0);
        if (workStatus == status) {
            return;
        } else {
            Settings.System.putInt(MyAppliacation.context.getContentResolver(), "showboom_work_status", status);
        }
    }

    public void updateScreenStatus() {
        boolean firstOpen = isFirstOpen();
        Log.d("leihuiming", "updateScreenStatus firstOpen = " + firstOpen);
        if (!firstOpen) {
            int workStatus = Settings.System.getInt(MyAppliacation.context.getContentResolver(), "showboom_work_status", 0);
            Log.d("leihuiming", "workStatus = " + workStatus);
            if (workStatus == 1) {
                screenOff();
                showStartWorkLayout();
            } else {
                screenOn();
                if (!MyAppliacation.signinStatus) {
                    showSiginErrorLayout();
                } else {
                    showStartWorkLayout();
                }
            }
        }
    }

    public static boolean isFirstOpen() {
        return (boolean) HmSharedPreferencesUtils.getParam("firstOpen", true);
    }

    public static void screenOff() {
        Log.d("leihuiming","screenOff");
        //Thread.dumpStack();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    //int brightness = Settings.System.getInt(MyAppliacation.context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
                    //if(brightness != 0) {
                    Settings.System.putInt(MyAppliacation.context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 0);
                    //} else {
                    //    CommandExecution.execCommand(CommandExecution.SCREEN_OFF, true);
                    //}
                    Util.setProperty("showboom.flipper.backlight", "0");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    public static void screenOn() {
        Log.d("leihuiming","screenOn");
        //Thread.dumpStack();
        new Thread(){
            @Override
            public void run() {
                super.run();
                Settings.System.putInt(MyAppliacation.context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 100);
                Util.setProperty("showboom.flipper.backlight", "1");
            }
        }.start();
    }

    public void startWork() {
        boolean signin = (boolean) HmSharedPreferencesUtils.getParam("signin", false);
        //boolean auth = (boolean) HmSharedPreferencesUtils.getParam("authentication", false);
        if (signin && Util.hasWifiConnection(this)) {
            Log.d("leihuiming", "startWork");
            updateWorkStatus(1);
            sendException("start_work");
        } else {
            Toast.makeText(this, "请连接WiFi并保证微信已经登录。", Toast.LENGTH_SHORT).show();
        }
    }

    public void startApp(String packageName) {
        try {
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "微信未安装", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    public static void sendException(final String exceptionReason) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Map<String, String> maps = new HashMap<>();
                maps.put("service", "abnormal");
                maps.put("imei", Util.getImei(MyAppliacation.context));
                maps.put("msg", exceptionReason);
                String result = HttpUtils.submitPostData(Util.exception_url, maps, "utf-8");

                if (!result.equals("-1") && !result.startsWith("err")) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 0) {
                            return;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public class SimCheckTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] objects) {
            String currentICCID = Util.getIccid();
            Map<String, String> param = new HashMap<>();
            param.put("service", "getDeviceMobile");
            param.put("imei", Util.getImei(MyAppliacation.context));
            param.put("iccid", currentICCID);
            String result = HttpUtils.submitPostData(Util.base_url, param, "utf-8");
            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String result = (String) o;
            if (!result.equals("-1") && !result.startsWith("err")) {
                try {
                    JSONObject object = new JSONObject(result);
                    int code = object.getInt("code");
                    if (code != 0) {
                        simStatus = false;
                        Log.d("leihuiming", "simErrorDialog == null " + (simErrorDialog == null));
                        //Log.d("leihuiming", "simErrorDialog.isShowing " + (simErrorDialog.isShowing()));
                        if(simErrorDialog == null) {
                            simErrorDialog = SimErrorDialog.createLoackScreenDialog(MainActivity.this);
                            sendException("nosim");
                            updateWorkStatus(0);
                            Log.d("leihuiming", "SIM CARD ERROR!");
                        } else {
                            if(!simErrorDialog.isShowing()) {
                                simErrorDialog.show();
                            } else {
                                Log.d("leihuiming", "SIM CARD ERROR, BUG DIALOG IS SHOWING!");
                            }
                        }
                    } else {
                        simStatus = true;
                        if(simErrorDialog != null && simErrorDialog.isShowing()) {
                            simErrorDialog.dismiss();
                        }
                        Log.d("leihuiming", "SIM CARD SUCCESS!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    simStatus = false;
                }
            } /*else {
                simStatus = false;
                sendException("nosim");
                updateWorkStatus(0);
            }*/
        }
    }

    public AsyncTask simCheckTast = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            String currentICCID = Util.getIccid();
            Map<String, String> param = new HashMap<>();
            param.put("service", "getDeviceMobile");
            param.put("imei", Util.getImei(MyAppliacation.context));
            param.put("iccid", currentICCID);
            String result = HttpUtils.submitPostData(Util.base_url, param, "utf-8");
            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String result = (String) o;
            if (!result.equals("-1") && !result.startsWith("err")) {
                try {
                    JSONObject object = new JSONObject(result);
                    int code = object.getInt("code");
                    if (code != 0) {
                        simStatus = false;
                        Log.d("leihuiming", "simErrorDialog == null " + (simErrorDialog == null));
                        //Log.d("leihuiming", "simErrorDialog.isShowing " + (simErrorDialog.isShowing()));
                        if(simErrorDialog == null) {
                            simErrorDialog = SimErrorDialog.createLoackScreenDialog(MainActivity.this);
                            sendException("nosim");
                            updateWorkStatus(0);
                            Log.d("leihuiming", "SIM CARD ERROR!");
                        } else {
                            if(!simErrorDialog.isShowing()) {
                                simErrorDialog.show();
                            }
                        }
                    } else {
                        simStatus = true;
                        if(simErrorDialog != null && simErrorDialog.isShowing()) {
                            simErrorDialog.dismiss();
                        }
                        Log.d("leihuiming", "SIM CARD SUCCESS!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    simStatus = false;
                }
            } /*else {
                simStatus = false;
                sendException("nosim");
                updateWorkStatus(0);
            }*/
        }
    };

    private void showSiginLayout() {
        siginLayout.setVisibility(View.VISIBLE);
        startWorkLayout.setVisibility(View.GONE);
        mainView.setBackgroundResource(R.mipmap.bg_guide);
    }

    private void showStartWorkLayout() {
        siginLayout.setVisibility(View.GONE);
        startWorkLayout.setVisibility(View.VISIBLE);
        mainView.setBackgroundResource(R.mipmap.bg_start_work);
    }

    private void showSiginErrorLayout() {
        siginLayout.setVisibility(View.VISIBLE);
        startWorkLayout.setVisibility(View.GONE);
        mainView.setBackgroundResource(R.mipmap.bg_signin_error);
    }

    private void showAuthErrorLayout() {
        siginLayout.setVisibility(View.VISIBLE);
        startWorkLayout.setVisibility(View.GONE);
        mainView.setBackgroundResource(R.mipmap.bg_auth_error);
    }


}
